package com.jinwei.qunguanjia.interceptor;

import com.jinwei.qunguanjia.common.core.domain.Response;
import com.jinwei.qunguanjia.common.core.domain.model.LoginUser;
import com.jinwei.qunguanjia.common.core.redis.RedisCache;
import com.jinwei.qunguanjia.common.enums.HttpResponseEnum;
import com.jinwei.qunguanjia.common.utils.JsonUtils;
import com.jinwei.qunguanjia.common.utils.StringUtils;
import com.jinwei.qunguanjia.common.utils.SystemContextUtils;
import com.jinwei.qunguanjia.user.service.UserTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

@Slf4j
@Component
public class UserLoginInterceptor implements HandlerInterceptor {

	@Resource
	private RedisCache redisCache;

	@Resource
	private UserTokenService tokenService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		// 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
        	response.setStatus(HttpStatus.OK.value());
            return Boolean.FALSE;
        }
        String token = tokenService.getToken(request);
        if(StringUtils.isNotBlank(token)){
        	boolean flag = false;
			LoginUser loginUser = null;
            if(!redisCache.exists(tokenService.getTokenKey(token))){
            	flag = true;
            } else {
				loginUser = redisCache.getCacheObject(tokenService.getTokenKey(token));
				if(null == loginUser){
					flag = true;
				}
			}
            if(flag){        	
            	responseJson(response);
    			return Boolean.FALSE;
            }else{
                SystemContextUtils.setCurrentSystemUser(loginUser);
                return Boolean.TRUE;
            }            
        }else{
        	responseJson(response);
        	return Boolean.FALSE;
        }
	}
	private void responseJson(HttpServletResponse response){
		String contentType = "application/json;charset=utf-8";
    	response.setContentType(contentType);
    	PrintWriter printWriter = null;
		try {
			printWriter = response.getWriter();
		} catch (IOException e) {
			log.error("JWTFilter isAccessAllowed Catch Exception: ",e);
		}
		Objects.requireNonNull(printWriter).append(JsonUtils.toJsonString(Response.fail(HttpResponseEnum.UNAUTHORIZED.getCode(), HttpResponseEnum.UNAUTHORIZED.getDesc())));
	}

}
